<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/4/30 11:36
 */


namespace App\Logic;

use App\Models\Common\OperationLog;
use App\Models\Common\ShortUrl;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\DB;

class CommLogic
{
    use AuthorizesRequests;
    
    /**
     * @param $sql
     * @return \Illuminate\Database\Query\Expression
     */
    public static function raw($sql)
    {
        return \DB::connection()->raw($sql);
    }

     /**
     * @param $count
     * @param string $prefix
     * @return string
     */
    public function createNo($count, $prefix = 'YTQ')
    {
        $count++;
        $count = $count % 999;
        if ($count < 100) {
            $s = intval(floor($count / 10));
            $y = $count % 10;
            $count = '0' . $s . $y;
        }
        return $prefix . date('Ymd') . $count;
    }

    public function getOperationSqlStart()
    {
        DB::enableQueryLog();
    }

    /**
     * @return string
     */
    public function getOperationSqlEnd()
    {
        $queries = DB::getQueryLog();
        $a = end($queries);
        $tmp = str_replace('?', '"' . '%s' . '"', $a["query"]);
        return vsprintf($tmp, $a['bindings']);
    }

    /**
     * 记录操作日志
     *
     * @param string $type
     * @param string $sql
     * @param string $remark
     * @param string $log_url
     * @param int $sid
     * @param string $name
     * @return bool
     */
    public function operationLog($type = '', $sql = '', $remark = '', $log_url = '', $sid = 0, $name = '')
    {
        if ($sql) {
            // 语句太长了,这样中文会有乱码
            $sql = mb_substr($sql, 0, 500, 'utf-8');
        }
        $add = array(
            'staffer_id' => $sid ? $sid : auth('api')->id(),
            'staffer_name' => $name ? $name : auth('api')->user()->name,
            'log_type' => $type,
            'log_ip' => get_client_ip(),
            'log_sql' => $sql ? $sql : '',
            'log_remark' => $remark,
            'log_url' => $log_url ? $log_url : request()->route()->getPrefix() . "/" . request()->route()->getActionMethod(),
        );
        return OperationLog::query()->insert($add);
    }

    /**
     * @param $longUrl
     * @param string $key
     * @return array
     */
    public function createShortUrl($longUrl, $key = '')
    {
        $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        // 利用md5算法方式生成hash值
        $hex = hash('md5', $longUrl . $key);
        $subHexLen = strlen($hex) / 8;
        $shortUrl = array();
        for ($i = 0; $i < $subHexLen; $i++) {
            // 将这32位分成四份，每一份8个字符，将其视作16进制串与0x3fffffff(30位1)与操作
            $subHex = substr($hex, $i * 8, 8);
            $idx = 0x3FFFFFFF & (1 * ('0x' . $subHex));
            // 这30位分成6段, 每5个一组，算出其整数值，然后映射到我们准备的62个字符
            $out = '';
            for ($j = 0; $j < 6; $j++) {
                $val = 0x0000003D & $idx;
                $out .= $base32[$val];
                $idx = $idx >> 5;
            }
            $shortUrl[$i] = $out;
        }
        ShortUrl::query()->create(array(
            'long_url' => $longUrl,
            'short_code' => $shortUrl,
        ));
        return compact('shortUrl');
    }

    /**
     * @param $shortUrl
     * @return mixed
     */
    public function getLongUrl($shortUrl)
    {
        $data = ShortUrl::query()->where('short_code', $shortUrl)->first();
        abort_if($data, 'not_find', '链接不存在');
        return $data->long_url;
    }
}
